﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Web;

namespace WindowsFormsApp1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		/// <summary>
		/// 截屏
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		#region 
		public struct RECT
		{
			public int left;
			public int top;
			public int right;
			public int bottom;
		}
		public struct POINT
		{
			int x;
			int y;
		}
		public static Bitmap GetWindowCapture(IntPtr hWnd)
		{
			IntPtr hscrdc = GetDC(hWnd);
			RECT windowRect = new RECT();
			GetWindowRect(hWnd, ref windowRect);
			int width = windowRect.right - windowRect.left;
			int height = windowRect.bottom - windowRect.top;
			IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
			IntPtr hmemdc = CreateCompatibleDC(hscrdc);
			SelectObject(hmemdc, hbitmap);
			PrintWindow(hWnd, hmemdc, 0);
			Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
			DeleteDC(hscrdc);//删除用过的对象
			DeleteDC(hmemdc);//删除用过的对象
			return bmp;
		}
		[DllImport("user32.dll")]
		public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);

		[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
		private static extern bool BitBlt(
		IntPtr hdcDest, // 目标 DC的句柄 
		int nXDest,
		int nYDest,
		int nWidth,
		int nHeight,
		IntPtr hdcSrc, // 源DC的句柄 
		int nXSrc,
		int nYSrc,
		System.Int32 dwRop // 光栅的处理数值 
		);
		[DllImport("gdi32.dll")]
		public static extern IntPtr CreateDC(
		 string lpszDriver,         // driver name驱动名
		 string lpszDevice,         // device name设备名
		 string lpszOutput,         // not used; should be NULL
		 IntPtr lpInitData   // optional printer data
		 );
		[DllImport("gdi32.dll")]
		public static extern int BitBlt(
		 IntPtr hdcDest, // handle to destination DC目标设备的句柄
		 int nXDest,   // x-coord of destination upper-left corner目标对象的左上角的X坐标
		 int nYDest,   // y-coord of destination upper-left corner目标对象的左上角的Y坐标
		 int nWidth,   // width of destination rectangle目标对象的矩形宽度
		 int nHeight, // height of destination rectangle目标对象的矩形长度
		 IntPtr hdcSrc,   // handle to source DC源设备的句柄
		 int nXSrc,    // x-coordinate of source upper-left corner源对象的左上角的X坐标
		 int nYSrc,    // y-coordinate of source upper-left corner源对象的左上角的Y坐标
		 UInt32 dwRop   // raster operation code光栅的操作值
		 );
		[DllImport("gdi32.dll")]
		public static extern IntPtr CreateCompatibleDC(
		 IntPtr hdc // handle to DC
		 );
		[DllImport("gdi32.dll")]
		public static extern IntPtr CreateCompatibleBitmap(
		 IntPtr hdc,         // handle to DC
		 int nWidth,      // width of bitmap, in pixels
		 int nHeight      // height of bitmap, in pixels
		 );
		[DllImport("gdi32.dll")]
		public static extern IntPtr SelectObject(
		 IntPtr hdc,           // handle to DC
		 IntPtr hgdiobj    // handle to object
		 );
		[DllImport("gdi32.dll")]
		public static extern int DeleteDC(
		 IntPtr hdc           // handle to DC
		 );
		[DllImport("user32.dll")]
		public static extern bool PrintWindow(
		 IntPtr hwnd,                // Window to copy,Handle to the window that will be copied.
		 IntPtr hdcBlt,              // HDC to print into,Handle to the device context.
		 UInt32 nFlags               // Optional flags,Specifies the drawing options. It can be one of the following values.
		 );
		[DllImport("user32.dll")]
		public static extern IntPtr GetDC(IntPtr hwnd);

		[DllImport("user32.dll")]
		static extern IntPtr WindowFromPoint(POINT Point);
		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		public static extern bool GetCursorPos(out POINT pt);
		#endregion


		private void button1_Click(object sender, EventArgs e)
		{
			//查找窗口
			System.Threading.Thread.Sleep(1000);
			POINT p = new POINT();
			GetCursorPos(out p);
			IntPtr wnd = WindowFromPoint(p);
			if (wnd != IntPtr.Zero)
			{
				this.button1.Text += "<找到窗口>";
				this.button1.Tag = wnd;
				//
			}
		}

		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{
			this.button2_Click(null, null);
		}

		protected string bClearHTML(string Content)
		{
			Content = Zxj_ReplaceHtml("&#[^>]*;", "", Content);
			Content = Zxj_ReplaceHtml("</?marquee[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?object[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?param[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?embed[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?table[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml(" ", "", Content);
			Content = Zxj_ReplaceHtml("</?tr[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?th[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?p[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?a[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?img[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?tbody[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?li[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?span[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?div[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?th[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?td[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?script[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("(javascript|jscript|vbscript|vbs):", "", Content);
			Content = Zxj_ReplaceHtml("on(mouse|exit|error|click|key)", "", Content);
			Content = Zxj_ReplaceHtml("<\\?xml[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("<\\/?[a-z]+:[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?font[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?b[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?u[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?i[^>]*>", "", Content);
			Content = Zxj_ReplaceHtml("</?strong[^>]*>", "", Content);
			string clearHtml = Content;
			return clearHtml;
		}
		private string Zxj_ReplaceHtml(string patrn, string strRep, string content)
		{
			if (string.IsNullOrEmpty(content))
			{
				content = "";
			}
			System.Text.RegularExpressions.Regex rgEx = new System.Text.RegularExpressions.Regex(patrn, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			string strTxt = rgEx.Replace(content, strRep);
			return strTxt;
		}
		public static string ClearHTML(string Htmlstring)
		{
			try
			{
				HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
				//Htmlstring = "<div id='container'>asdfasdfa</div>";
				doc.LoadHtml(Htmlstring);
				HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='c-abstract']");
				if (nodes != null)
				{
					Htmlstring = "";
					for (int i = 0; i < nodes.Count; i++)
					{
						Htmlstring+= nodes[i].InnerText;
					}
					return Htmlstring;
				}
				else return "";
			}
			catch
			{
				return "";
			}






			//删除脚本  
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			//删除HTML  
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"-->", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<!--.*", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(amp|#38);", "&", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(lt|#60);", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(gt|#62);", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&#(\d+);", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			Htmlstring.Replace("<", "");
			Htmlstring.Replace(">", "");
			Htmlstring.Replace("\r\n", "");
			Htmlstring = System.Net.WebUtility.HtmlDecode(Htmlstring).Replace("<br/>", "\n").Replace("<br>", "\n").Trim();
			return Htmlstring;
		}
		public static string ToUrlEncode(string strCode)
		{
			StringBuilder sb = new StringBuilder();
			byte[] byStr = System.Text.Encoding.UTF8.GetBytes(strCode);
			System.Text.RegularExpressions.Regex regKey = new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$");
			for (int i = 0; i < byStr.Length; i++)
			{
				string strBy = Convert.ToChar(byStr[i]).ToString();
				if (regKey.IsMatch(strBy))
				{
					//是字母或者数字则不进行转换
					sb.Append(strBy);
				}
				else
				{
					sb.Append(@"%" + Convert.ToString(byStr[i], 16));
				}
			}
			return (sb.ToString());
		}
		private string GetWebClient(string url)
		{
			string strHTML = "";
			System.Net.WebClient myWebClient = new System.Net.WebClient();
			System.IO.Stream myStream = myWebClient.OpenRead(url);
			System.IO.StreamReader sr = new System.IO.StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));
			strHTML = sr.ReadToEnd();
			myStream.Close();
			return strHTML;
		}
		private void button2_Click(object sender, EventArgs e)
		{
			//// 窗口截图
			IntPtr hWnd = (IntPtr)this.button1.Tag;
			RECT windowRect = new RECT();
			GetWindowRect(hWnd, ref windowRect);
			int width = windowRect.right - windowRect.left;
			int height = (windowRect.bottom - windowRect.top) * 60 / 100;
			IntPtr hscrdc = GetDC(hWnd);
			IntPtr hmemdc = CreateCompatibleDC(IntPtr.Zero);
			IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
			SelectObject(hmemdc, hbitmap);
			BitBlt(hmemdc, 0, 0, width, height, hscrdc, 0, 0, 0xCC0020 | 0x40000000);
			//PrintWindow(hWnd, hmemdc, 0);
			Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
			DeleteDC(hscrdc);//删除用过的对象
			DeleteDC(hmemdc);//删除用过的对象
							 // return bmp;
			bmp.Save("z:\\aaaa.bmp");


			

			//// 开始OCR
			string APP_ID = "10632123";
			string API_KEY = "9BQg8QLHyaLC06tqyUiQZVSw";
			string SECRET_KEY = "cXZlrYzPt8LKtAh2ETPTNTFQeU6aIDKK";
			Baidu.Aip.Ocr.Ocr client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
			//var image = System.IO.File.ReadAllBytes();
			// 调用通用文字识别, 图片参数为本地图片，可能会抛出网络等异常，请使用try/catch捕获
			Newtonsoft.Json.Linq.JObject result;
			using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
			{
				bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
				byte[] data = new byte[stream.Length];
				stream.Seek(0, System.IO.SeekOrigin.Begin);
				stream.Read(data, 0, Convert.ToInt32(stream.Length));
				result = client.GeneralBasic(data);
			}
			var w = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(result["words_result"].ToString());
			string s = "";
			for (int i = 0; i < w.Count; i++)
			{
				s += w[i]["words"].ToString();
			}
			// this.richTextBox1.Text = s;
			s = "好人一生平安";
			//// 搜索
			s = GetWebClient("http://www.baidu.com/s?wd=" + ToUrlEncode(s) + "&ie=UTF-8");
			/*
			if (s.IndexOf("<div id=\"container\" class=\"container_s\">") > 0)
				s = s.Substring(s.IndexOf("<div id=\"container\" class=\"container_s\">"));
			if (s.IndexOf("<div class=\"tt\">相关搜索</div>") > 0)
				s = s.Substring(0,s.IndexOf("<div class=\"tt\">相关搜索</div>"));
			*/
			s = ClearHTML(s);
			this.richTextBox1.Text = s;
			//s = ClearHTML(s);
		}
	}
}
